package uniandes.dermatologia;

import rajawali.RajawaliActivity;
import uniandes.dermatologia.models.PhysicalExamination;
import uniandes.dermatologia.resources.Constants;
import uniandes.dermatologia.resources.Render;
import uniandes.dermatologia.singleton.DermatologiaUniandesApp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.FloatMath;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

public class BodyActivity extends RajawaliActivity implements
		View.OnClickListener {
	private static final String TAG = "BodyParts";

	private ProgressBar loaderGraphic;
	private Render renderer;
	private GestureDetector gestureDetector;
	private View.OnTouchListener gestureListener;
	private View.OnTouchListener buttonListener;
	private static final int NONE = 0;
	private static final int DRAG = 1;
	private static final int ZOOM = 2;
	private int mode = NONE;

	PointF start = new PointF();
	PointF mid = new PointF();
	float oldDist = 1f;
	boolean rotando = false;

	private RelativeLayout relativeLayout;
	private Button btnRight;
	private Button btnLeft;

	@Override
	@SuppressWarnings("deprecation")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		getActionBar().setDisplayHomeAsUpEnabled(false);

		setGLBackgroundTransparent(true);
		renderer = new Render(this);
		mLayout.setBackgroundColor(Color.parseColor("#E6E6E6"));
		renderer.setSurfaceView(mSurfaceView);
		super.setRenderer(renderer);

		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		relativeLayout = (RelativeLayout) inflater.inflate(
				R.layout.activity_body, null);

		mLayout.addView(relativeLayout);

		loaderGraphic = (ProgressBar) findViewById(R.id.loaderBody);
		btnRight = (Button) findViewById(R.id.btnRight);
		btnLeft = (Button) findViewById(R.id.btnLeft);
		buttonListener = new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction() & MotionEvent.ACTION_MASK) {
				case MotionEvent.ACTION_DOWN:
					if (v.getId() == R.id.btnRight) {
						renderer.iniciarAnimacionDerecha();
					} else if (v.getId() == R.id.btnLeft) {
						renderer.iniciarAnimacionIzquierda();
					}
					break;
				case MotionEvent.ACTION_UP:
					if (v.getId() == R.id.btnRight) {
						renderer.detenerAnimacionDerecha();
					} else if (v.getId() == R.id.btnLeft) {
						renderer.detenerAnimacionIzquierda();
					}
					break;
				}
				return false;
			}

		};

		btnRight.setOnTouchListener(buttonListener);
		btnLeft.setOnTouchListener(buttonListener);

		gestureDetector = new GestureDetector(new MyGestureDetector());
		gestureListener = new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				switch (event.getAction() & MotionEvent.ACTION_MASK) {

				case MotionEvent.ACTION_DOWN:
					start.set(event.getX(), event.getY());
					mode = DRAG;
					break;

				case MotionEvent.ACTION_POINTER_DOWN:

					oldDist = spacing(event);
					if (oldDist > 10f) {
						midPoint(mid, event);
						mode = ZOOM;
					}
					break;

				case MotionEvent.ACTION_UP:

				case MotionEvent.ACTION_POINTER_UP:
					mode = NONE;
					renderer.pinchOrDragFinished();
					break;

				case MotionEvent.ACTION_MOVE:

					if (mode == DRAG) {
						float x = event.getX() - start.x, y = event.getY()
								- start.y;
						if (Math.abs(x) > 10f || Math.abs(y) > 10f)
							renderer.drag(x, y);
					} else if (mode == ZOOM) {
						float newDist = spacing(event);
						if (newDist > 10f) {
							float scale = newDist / oldDist;
							renderer.pinch(scale);
						}
					}
					break;
				}

				return gestureDetector.onTouchEvent(event);
			}
		};

		mSurfaceView.setOnClickListener(this);
		mSurfaceView.setOnTouchListener(gestureListener);

	}

	public void hideLoader() {

		relativeLayout.post(new Runnable() {
			@Override
			public void run() {
				loaderGraphic.setVisibility(View.INVISIBLE);

				btnRight.setVisibility(View.VISIBLE);
				btnLeft.setVisibility(View.VISIBLE);
				mLayout.removeView(loaderGraphic);
			}
		});
	}

	class MyGestureDetector extends SimpleOnGestureListener {

		@Override
		public boolean onSingleTapConfirmed(MotionEvent event) {

			Log.d(TAG, "onSingleTapConfirmed");
			renderer.singleTap(event.getX(), event.getY());
			return true;
		}

		@Override
		public boolean onDoubleTapEvent(MotionEvent event) {
			Log.d(TAG, "onDoubleTapEvent");
			renderer.doubleTap(event.getX(), event.getY());
			return true;
		}
	}

	@Override
	public void onClick(View arg0) {

	}

	private float spacing(MotionEvent event) {
		return distance(event.getX(0), event.getX(1), event.getY(0),
				event.getY(1));
	}

	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}

	private float distance(float x1, float x2, float y1, float y2) {
		float x = x1 - x2, y = y1 - y2;
		return FloatMath.sqrt(x * x + y * y);
	}

	public void onClickBack(View v) {

		finish();

	}

	public void onClickNext(View v) {

		if (informacionValida()) {
			Intent intent = new Intent(this, BorderActivity.class);
			// Intent intent = new Intent(this, DistributionActivity.class);
			startActivity(intent);
			PhysicalExamination pe = ((DermatologiaUniandesApp) getApplication())
					.getCurrentConsultation().getPhysicalExamination();
			pe.setAffectedAreas(renderer.getEstaSeleccionadoModelo());
			String result = "";
			for (int i = 0; i < pe.getAffectedAreas().length; i++) {
				if (pe.getAffectedAreas()[i]) {
					result = result + ","
							+ Constants.AFFECTED_AREAS_REST_MSG[i];

				}
			}
			if (result.charAt(0) == ',') {
				result = result.substring(1, result.length());
			}
			pe.setBodyParts(result);
			// finish();
		} else {
			AlertDialog ad = new AlertDialog.Builder(this).create();
			ad.setCancelable(false);
			ad.setTitle(R.string.title_activity_body);
			ad.setMessage(getString(R.string.body_error));
			ad.setButton(DialogInterface.BUTTON_NEUTRAL,
					getString(R.string.close_alert_dialog),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			ad.show();
		}
	}

	private boolean informacionValida() {
		boolean haySeleccion = false;
		for (int i = 0; i < renderer.getEstaSeleccionadoModelo().length; i++) {
			if (renderer.getEstaSeleccionadoModelo()[i]) {
				haySeleccion = true;
			}
		}
		return haySeleccion;
	}

}
